package org.minbox.framework.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.Assert;

/**
 * The json utils
 *
 * @author 恒宇少年
 * @since 1.0.5
 */
public class JsonUtils {
    /**
     * beautify object to json
     *
     * @param object object
     * @return object json string
     */
    public static String beautifyJson(Object object) {
        Assert.notNull(object, "The wait beautify object cannot be null.");
        try {
            ObjectMapper mapper = new ObjectMapper();
            return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        throw new IllegalArgumentException("Unable to format json.");
    }

    /**
     * beautify string to json
     *
     * @param json json string
     * @return after beautify json
     */
    public static String beautifyJson(String json) {
        Assert.notNull(json, "The wait beautify json string cannot be null.");
        try {
            ObjectMapper mapper = new ObjectMapper();
            Object object = mapper.readValue(json, Object.class);
            return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        throw new IllegalArgumentException("Unable to format json.");
    }

    /**
     * Object conversion string
     *
     * @param object Object waiting to convert json string
     * @return Converted json
     */
    public static String toJsonString(Object object) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        throw new IllegalArgumentException("Unable to format json.");
    }

    /**
     * String conversion object
     *
     * @param json The json string
     * @param <T>  The return type
     * @return The return instance
     */
    public static <T> T fromJsonString(String json) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            return (T) mapper.readValue(json, Object.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        throw new IllegalArgumentException("Unable to format json.");
    }
}
